package timeTask

import (
	"encoding/json"
	"fmt"
	"github.com/e421083458/golang_common/lib"
	"github.com/gogf/gf/container/gmap"
	"github.com/gogf/gf/os/gfile"
	"github.com/gogf/gf/os/glog"
	"github.com/gogf/gf/os/gtimer"
	"github.com/gogf/gf/util/gconv"
	"rock/customer/dto"
	"rock/customer/initParam"
	"rock/customer/middleware"
	"rock/customer/modules/taskMap"
	"time"
)

//初始化，从文件中获取中断时间的任务，中断期间会以json格式保存任务
func Start() {
	var a = make(map[string]taskMap.SendMap, 0)
	sm := gfile.GetBytes(taskMap.Path)
	if string(sm) != "" {
		err := json.Unmarshal(sm, &a)
		if err != nil {
			glog.Error(err)
			return
		}
		//放入listmap
		for _, v := range a {
			taskMap.M.Set(v.ToUserID, taskMap.SendMap{
				FromUserID: v.FromUserID,
				ToUserID:   v.ToUserID,
				Content:    v.Content,
				ChatType:   v.ChatType,
				TimeStamp:  v.TimeStamp,
				Type:       v.Type,
			})
		}
	}
}

//删除
func Delete(toUserID string) {
	taskMap.M.Remove(toUserID)
	fmt.Println(taskMap.M.String())
}

//中断时将数据写入send_map.txt
func Interrupt() {
	text, err := taskMap.M.MarshalJSON()
	if err != nil {
		glog.Error(err)
		return
	}
	err = gfile.PutContents(taskMap.Path, string(text))
	if err != nil {
		glog.Error(err)
		return
	}
}

func quitGroup(queryParam dto.Group) {
	//发送系统消息
	paramJsonBytes, err := json.Marshal(queryParam)
	if err != nil {
		fmt.Println(err)
		glog.Error(err)
	}
	paramJsonStr := string(paramJsonBytes)
	queryUrl := initParam.BaseConf.Host + "/mgroupstate"
	_, queryByte, err := lib.HttpJSON(lib.NewTrace(), queryUrl, paramJsonStr, 60*1000, nil)
	if err != nil {
		fmt.Println(err)
		glog.Error(err)
	}
	resp := &middleware.Response{}
	if err := json.Unmarshal(queryByte, resp); err != nil {
		fmt.Println(err)
		glog.Error(err)
	}
	if resp.ErrorCode != middleware.SUCCESS_CODE {
		fmt.Println(err)
		glog.Error(err)
	}
}

//发送消息
func Send(queryParam dto.Group) {
	//发送系统消息
	paramJsonBytes, err := json.Marshal(queryParam)
	if err != nil {
		fmt.Println(err)
		glog.Error(err)
	}
	paramJsonStr := string(paramJsonBytes)
	queryUrl := initParam.BaseConf.Host + "/sendwelcomemsg"
	_, queryByte, err := lib.HttpJSON(lib.NewTrace(), queryUrl, paramJsonStr, 60*1000, nil)
	if err != nil {
		fmt.Println(err)
		glog.Error(err)
	}
	resp := &middleware.Response{}
	if err := json.Unmarshal(queryByte, resp); err != nil {
		fmt.Println(err)
		glog.Error(err)
	}
	if resp.ErrorCode != middleware.SUCCESS_CODE {
		fmt.Println(err)
		glog.Error(err)
	}
}

//初始化
func InitTimer() {
	//初始化gmap.listmap
	taskMap.M = gmap.NewListMap(true)
	//初始化，从文件中获取中断时间的任务，中断期间会以json格式保存任务
	Start()
	//遍历listmap
	gtimer.AddSingleton(taskMap.IntervalTime, func() {
		if taskMap.M.Size() > 0 {
			isPop := 0
			mapKey := ""
			taskMap.M.Iterator(func(key, value interface{}) bool {
				valueSendMap := value.(taskMap.SendMap)
				switch valueSendMap.Type.Val() {
				case "quit":
					if valueSendMap.TimeStamp.Val() < gconv.Int(time.Now().Unix()) {
						quitGroup(dto.Group{
							GroupId: valueSendMap.ToUserID.String(),
							State:   2,
						})
						mapKey = key.(string)
						isPop = 1
						return false
					}
				case "sendToCs":
					if valueSendMap.TimeStamp.Val() < gconv.Int(time.Now().Unix()) {
						Send(dto.Group{
							UserId:      valueSendMap.FromUserID.String(),
							GroupId:     valueSendMap.ToUserID.String(),
							OtherUserId: key.(string),
							Msg:         valueSendMap.Content.String(),
							MsgType:     8,
						})
						mapKey = key.(string)
						isPop = 1
						return false
					}
				case "sendToC":
					if valueSendMap.TimeStamp.Val() < gconv.Int(time.Now().Unix()) {
						Send(dto.Group{
							UserId:      valueSendMap.FromUserID.String(),
							GroupId:     valueSendMap.ToUserID.String(),
							OtherUserId: key.(string),
							Msg:         valueSendMap.Content.String(),
							MsgType:     21,
						})
						mapKey = key.(string)
						isPop = 1
						//添加一个三分钟的 退出群聊
						return false
					}
				case "question", "invitation":
					//FromUserID 被转接或被邀请的用户id，ToUserID 群id
					if valueSendMap.TimeStamp.Val() < gconv.Int(time.Now().Unix()) {
						Send(dto.Group{
							UserId:  valueSendMap.FromUserID.String(),
							GroupId: valueSendMap.ToUserID.String(),
							MsgType: 18,
							//存类型
							Msg: valueSendMap.Type.Val(),
							//存私聊群id
							Extra: valueSendMap.PrivateGroupId.Val(),
							//
							MsgUid: valueSendMap.MsgUid.String(),
						})
						mapKey = key.(string)
						isPop = 1
						return false
					}
					break
				}
				return true
			})
			if isPop == 1 {
				Delete(mapKey)
				isPop = 0
			}
		}
		//else {
		//	fmt.Println("list is null")
		//}
		time.Sleep(taskMap.IntervalSleepTime)
	})
	//测试
	//fromUserId := "125651"
	//toUserId := "16764811434004480"
	//content := "iii"
	//timeout := gconv.String(time.Now().Add(time.Duration(5) * time.Second).Unix())
	//key := toUserId + "_customer"
	//gtimer.AddOnce(20*time.Second, func() {
	//	send(key, SendMap{
	//		FromUserID: gtype.NewString(fromUserId),
	//		ToUserID:   gtype.NewString(toUserId),
	//		Content:    gtype.NewString(content),
	//		ChatType:   gtype.NewString("group"),
	//		TimeStamp:  gtype.NewInt(gconv.Int(timeout)),
	//	})
	//})
}
